/**
 * Created by Xiaobing on 2016/8/25.
 * 家客 质差小区分析
 */
function BroadbandCus() {
    var time = "";//时间
    var time_dim_id = "60";
    var region = {
        id: 1,
        type: 9000
    };//地市
    var select_cell_id = "";
    var isFirst = false;
    var cell_layer = gis_core.addGraphicsLayer("BroadbandCus_cell_layer", "小区图层");
    var marker_layer = gis_core.addGraphicsLayer("BroadbandCus_marker_layer", "标记图层");
    //事件
    var cellLayer_click_handle = null;

    //地图改变事件
    var extentchange = function (delta) {
        getBadCells();
    };
    //加载表格值差小区
    var loadDadCellListTablle = function () {
        var content = "<div>";
        content += "<table id='BroadbandCus_BadCells_Table'></table>";
        content += "<div id='BroadbandCus_BadCells_Pager'></div>"
        content += "<div>";
        var div = $(content);

        gis_layout.createLeftWidget("BroadbandCus_BadCells_JQGrid_Div", "质差小区明细", div);

        div.find("#BroadbandCus_BadCells_Table").jqGrid({
            url: '/getbadcelllistjqgrid?isdegradecell=1&time=' + time + '&timedimid=' + time_dim_id + "&region=" + JSON.stringify(region),
            datatype: "json",
            width: 400,
            height:230,
            colNames: ['ID', '时间', '小区名称', '地市', '经度', '纬度'],
            colModel: [{
                name: 'id',
                index: 'id',
                width: 50,
                hidden: true
            }, {
                name: 'tag',
                index: 'tag',
                width: 30
            }, {
                name: 'name',
                index: 'name',
                width: 80
            }, {
                name: 'cityName',
                index: 'cityName',
                width: 20,
                align: "right"
            }, {
                name: 'longitude',
                index: 'longitude',
                width: 30,
                align: "right"
            }, {
                name: 'latitude',
                index: 'latitude',
                width: 30,
                align: "right"
            }
            ],
            rowNum: 10,
            rowList: [10, 20, 30, 50],
            pager: '#BroadbandCus_BadCells_Pager',
            mtype: "get",
            viewrecords: true,
            caption: "",
            onSelectRow: function (id) {
                var data = div.find("#BroadbandCus_BadCells_Table").jqGrid('getRowData', id);
                select_cell_id = data.id;
                gis_common.setExtent(parseFloat(data.longitude) + 0.005, parseFloat(data.latitude) + 0.005, parseFloat(data.longitude) - 0.005, parseFloat(data.latitude) - 0.005);
                getBadCellKpiDetail(data.id);
            }
        });
    };
    //加载地图值差小区数据
    var getBadCells = function () {
        cell_layer.clear();
        if (time == null || time == "") {
            return;
        }
        $.ajax({
            url: "/getbadcelllist",
            data: {
                extent: JSON.stringify(gis_common.getMapExtent()),
                region: JSON.stringify(region),
                time: time,
                timedimid: time_dim_id
            },
            dataType: "json",
            async: true,
            type: "GET",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                gis_common.outPut(req, function (datas) {
                    var btses = eval(datas);
                    createCellCover(btses);
                });
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };
    var createCellCover = function (btses) {
        var xmax = 0.0, ymax = 0.0, xmin = 0.0, ymin = 0.0;

        for (var i = 0; i < btses.length; i++) {
            var bts = btses[i];

            if (xmax == 0.0) {
                xmax = bts.longitude;
                xmin = bts.longitude;
                ymax = bts.latitude;
                ymin = bts.latitude;
            }
            else {
                xmax = bts.longitude > xmax ? bts.longitude : xmax;
                xmin = bts.longitude < xmin ? bts.longitude : xmin;
                ymax = bts.latitude > ymax ? bts.latitude : ymax;
                ymin = bts.latitude < ymin ? bts.latitude : ymin;
            }

            if (bts.tag == "cluster") {
                var point = new esri.geometry.Point(bts.longitude, bts.latitude, gis_core.map.spatialReference);

                var symbol = new esri.symbol.PictureMarkerSymbol('/images/cluster.png', 48, 48);
                var graphic = new esri.Graphic(point, symbol);
                cell_layer.add(graphic);

                var text = bts.value + "";
                if (bts.value >= 1000) {
                    text = (bts.value / 1000).toFixed(2) + "万"
                }
                var textSymbol = new esri.symbol.TextSymbol(text);
                textSymbol.setAlign(esri.symbol.TextSymbol.ALIGN_MIDDLE);
                textSymbol.setColor(new esri.Color([255, 255, 255, 1]));
                textSymbol.setOffset(0, -5);
                var textgraphic = new esri.Graphic(point, textSymbol);
                cell_layer.add(textgraphic);
            }
            else {
                var antbw = 30;
                var azimuth = 0;
                var off_azimuth = 0;
                if (bts.cells.length > 1) {
                    antbw = 180.0 / bts.cells.length;
                    off_azimuth = 360.0 / bts.cells.length;
                }
                if (antbw > 30) {
                    antbw = 30;
                }

                for (var j = 0; j < bts.cells.length; j++) {
                    var cell = bts.cells[j];
                    cell.radius = 200;
                    cell.antbw = antbw;
                    if (cell.azimuth == 0) {
                        cell.azimuth = azimuth;
                    }
                    var g = gis_common.createCellGraphic(cell);
                    cell_layer.add(g);
                    azimuth = azimuth + off_azimuth;

                    if (!gis_common.stringIsNullOrWhiteSpace(select_cell_id) && select_cell_id == cell.id) {
                        marker_layer.clear();
                        var rings = gis_common.createCellCoverRing(cell.longitude, cell.latitude, cell.radius, cell.azimuth, cell.antbw);
                        var p = rings[rings.length / 2];
                        var x = cell.longitude - (cell.longitude - p[0]) / 2;
                        var y = cell.latitude - (cell.latitude - p[1]) / 2;

                        marker_layer.clear();
                        var point = new esri.geometry.Point(x, y, gis_core.map.spatialReference);
                        var symbol = new esri.symbol.PictureMarkerSymbol('/images/point.png', 28, 28);
                        var graphic = new esri.Graphic(point, symbol);
                        marker_layer.add(graphic);
                    }
                }
            }
        }
        if (xmax > 0.0 && isFirst == true) {
            gis_common.setExtent(xmax + 0.005, ymax + 0.005, xmin - 0.005, ymin - 0.005);
            isFirst = false;
        }
    };
    var getBadCellKpiDetail = function (cellid) {
        $.ajax({
            url: "/getbadcellkpidetail",
            data: {
                region: JSON.stringify(region),
                time: time,
                timedimid: time_dim_id,
                cellid: cellid
            },
            dataType: "json",
            async: true,
            type: "GET",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                gis_common.outPut(req, function (data) {
                    var div = gis_common.createKeyValueList(data);
                    gis_layout.createRightWidget("BroadbandCus_getBadCellKpiDetailHtml", "小区指标明细", div);
                });
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };

    /**
     * 初始化
     */
    this.init = function () {
        gis_core.addPlugin(this);
        //加载库文件
        gis_core.addExtentChange("broadbandcus_extentchange", extentchange);
        //注册事件
        if (cellLayer_click_handle != null) {
            dojo.disconnect(cellLayer_click_handle);
        }
        cellLayer_click_handle = cell_layer.on("click", function (evt) {
            var cell = evt.graphic.attributes.data;
            getBadCellKpiDetail(cell.id);
        });

    };
    /**
     * 销毁
     */
    this.destroy = function () {
        gis_core.removeExtentChange("realrimemonitoring_extentchange");
        gis_layout.removeLeftWidget();
        gis_layout.removeRightWidget();
    };
    /**
     * 模块信息
     * @type {{id: string, name: string}}
     */
    this.title = {
        id: "00_06_00",
        name: "家客"
    };
    /**
     * 清理
     */
    this.clear = function () {
        gis_layout.removeLeftWidget();
        gis_layout.removeRightWidget();
        marker_layer.clear();
        cell_layer.clear();
    };
    //值差小区查询条件面板
    this.createQueryHtml = function (callback) {
        gis_layout.removeLeftWidget();
        gis_layout.removeRightWidget();
        gis_resources.getRegions(function (data) {
            var content = "";
            content += "<div class='form-group'>";
            content += "	<label for='' class='col-sm-3 control-label'>时间粒度:</label>";
            content += " 	<div class='col-sm-9'>";
            content += "		<select id='BroadbandCus_query_param_time_dim_id_select' class='form-control'>";
            content += "            <option neid='60' select='selected'>天</option>";
            content += "            <option neid='62' >月</option>";
            content += "            <option neid='40' >小时</option>";
            content += "		</select>";
            content += "	</div>";
            content += "</div>";

            content += "<div class=\"form-group\">";
            content += "	<label class='col-sm-3 control-label'>查询时间:</label>";
            content += "	<div id='BroadbandCus_query_param_time_div' class='col-sm-9'>";
            content += "			<input id='BroadbandCus_query_param_time' type='text' class='form-control' onFocus=\"WdatePicker({lang:'zh-cn',dateFmt:'yyyy-MM-dd'});\"/>";
            content += " 	</div > ";
            content += " </div > "

            content += "<div class='form-group'>";
            content += "	<label for='' class='col-sm-3 control-label'>地市:</label>";
            content += " 	<div class='col-sm-9'>";
            content += "		<select id='BroadbandCus_query_param_region_select' class='form-control'>";
            if (data != null && data != undefined && data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    var r = data[i];
                    content += "<option neid='" + r.id + "' netype='" + r.type + "'>" + r.name + "</option>";
                }
            } else {
                content += "<option neid='1' netype='9000'>全部</option>";
            }
            content += "		</select>";
            content += "	</div>";
            content += "</div>";

            /*content += "<div class='form-group'>";
            content += "	<label for='' class='col-sm-3 control-label'>带宽:</label>";
            content += " 	<div class='col-sm-9'>";
            content += "		<select id='BroadbandCus_query_param_daikuang_select' class='form-control'>";
            content += "            <option neid='1' netype='9000'>10M</option>";
            content += "            <option neid='1' netype='9000'>12M</option>";
            content += "            <option neid='1' netype='9000'>50M</option>";
            content += "            <option neid='1' netype='9000'>其他</option>";
            content += "		</select>";
            content += "	</div>";
            content += "</div>";*/

            content += "<div class='form-group'>";
            content += " 	<div class='col-sm-9 col-sm-offset-3'>";
            content += "		<button id='BroadbandCus_query_param_btn_load' class='btn btn-primary'>确 定</button>";
            content += "	</div>";
            content += "</div>";

            var div = $(content);
            //时间粒度选取  联动
            div.find("#BroadbandCus_query_param_time_dim_id_select").bind("change", function (e) {
                time_dim_id = $(this).children('option:selected').attr("neid");
                var time_div = $("#BroadbandCus_query_param_time_div");
                time_div.html("");
                if (time_dim_id == "60") {
                    var d = new Date().Format("yyyy-MM-dd");
                    time_div.append("<input id='BroadbandCus_query_param_time' type='text' class='form-control' value='" + d + "' onFocus=\"WdatePicker({lang:'zh-cn',dateFmt:'yyyy-MM-dd'});\"/>");
                }
                else if (time_dim_id == "62") {
                    var d = new Date().Format("yyyy-MM");
                    time_div.append("<input id='BroadbandCus_query_param_time' type='text' class='form-control' value='" + d + "' onFocus=\"WdatePicker({lang:'zh-cn',dateFmt:'yyyy-MM'});\"/>");
                }
                else if (time_dim_id == "40") {
                    var d = new Date().Format("yyyy-MM-dd hh");
                    time_div.append("<input id='BroadbandCus_query_param_time' type='text' class='form-control' value='" + d + "' onFocus=\"WdatePicker({lang:'zh-cn',dateFmt:'yyyy-MM-dd HH'});\"/>");
                }
            });

            div.find("#BroadbandCus_query_param_btn_load").bind("click", function (e) {
                time = div.find("#BroadbandCus_query_param_time").val().replace(/-/g, '').replace(/:/g, '').replace(/ /g, '');
                if (gis_common.stringIsNullOrWhiteSpace(time)) {
                    gis_common.showMessage("请选择时间");
                    div.find("#BroadbandCus_query_param_time").focus();
                    return;
                }
                //地市
                var selects = $("#BroadbandCus_query_param_region_select option:selected");
                if (selects != null && selects != undefined) {
                    region.id = selects.attr("neid");
                    region.type = selects.attr("netype");
                } else {
                    gis_common.showMessage("请选择地市");
                    div.find("#BroadbandCus_query_param_region_select").focus();
                    return;
                }
                //临时添加
                isFirst = true;
                loadDadCellListTablle();
                getBadCells();
            });

            var d = new Date().Format("yyyy-MM-dd");
            div.find("#BroadbandCus_query_param_time").val(d);
            callback(div);
        });
    };
    this.initQuery = function (cityid, tim, timdimid, cellid) {
        gis_resources.getRegions(function (data) {
            var isregion = false;
            for (var i = 0; i < data.length; i++) {
                var r = data[i];
                if (r.id == cityid) {
                    region.id = cityid;
                    region.type = r.type;
                    isregion = true;
                    break;
                }
            }
            if (isregion == false) {
                gis_common.showMessage("地市信息错误");
                return;
            }
            time = tim;
            time_dim_id = timdimid;

            isFirst = true;
            if (!gis_common.stringIsNullOrWhiteSpace(cellid)) {
                select_cell_id = cellid;
                getBadCellKpiDetail(cellid);
            }
            loadDadCellListTablle();
            getBadCells();
        });
    };
}

var broadbandCus = null;
//初始化
function initBroadbandCus() {
    if (broadbandCus == null) {
        broadbandCus = new BroadbandCus();
        broadbandCus.init();
    }
}
//值差小区查询
function BroadbandCus_createQueryHtml(obj) {
    initBroadbandCus();
    gis_layout.createMenubarWithFun("BroadbandCus_createQueryHtml", obj, "质差小区", broadbandCus.createQueryHtml);
}

function BroadbandCus_Init_Qyery() {
    initBroadbandCus();
    broadbandCus.clear();
    var cityid = gis_common.getQueryString("cityid");
    var time = gis_common.getQueryString("time");
    var timedimid = gis_common.getQueryString("timedimid");
    var cellid = gis_common.getQueryString("cellid");
    if (gis_common.stringIsNullOrWhiteSpace(cityid) || gis_common.stringIsNullOrWhiteSpace(timedimid)) {
        return;
    }
    broadbandCus.initQuery(cityid, time, timedimid, cellid);
}
